/**
 * 
 */
package org.adorsys.aderp.cash.work.encashment;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.adorsys.aderp.cash.domain.CashReceipt;
import org.adorsys.aderp.cash.domain.CashRegItem;
import org.adorsys.aderp.cash.service.CashRegisterService;
import org.adorsys.aderp.jpa.security.SecurityUtils;
import org.springframework.util.Assert;

/**
 * @author Boris Waguia
 * 
 */

public class BasicEncashment  {
	private static List<EncashmentSession> encashmentSessions = new ArrayList<EncashmentSession>();
	@Resource
	private static CashRegisterService cashRegisterService;
	
	public BasicEncashment(){}
	
	public static CashReceipt getCashReceipt(){
		CashReceipt cashReceipt = new CashReceipt();
		EncashmentSession activeEncashmentSession = getActiveEncashmentSession();
		if(activeEncashmentSession == null)throw new IllegalStateException("No active cash session was found please start another one");
		List<CashRegItem> cashRegItems = activeEncashmentSession.getCashRegItems();
		//sum the total amount
		System.out.println(cashRegItems.toString());
		BigDecimal totalAmount = BigDecimal.ZERO;
		for (CashRegItem cashRegItem : cashRegItems) {
			totalAmount = totalAmount.add(cashRegItem.getAmount());
		}
		System.out.println(" total purchase "+totalAmount);
		String cashier = SecurityUtils.getUserName();
		cashReceipt.setCashReceiptKey("nfog0nslss0sn");
		cashReceipt.setTotalPurchase(totalAmount);
		cashReceipt.setAmountDue(BigDecimal.ZERO);
		cashReceipt.setAmountIn(BigDecimal.ZERO);
		cashReceipt.setAmountOut(BigDecimal.ZERO);
		cashReceipt.setTax(BigDecimal.ZERO);
		cashReceipt.setGratuity(BigDecimal.ZERO);
		cashReceipt.setCashDate(new Date());
		cashReceipt.setCashier(cashier);
		cashReceipt.setApprovedBy("");
		cashReceipt.setReceiptNumber("kw0e;ed9dps-s");
//		cashReceipt.setCashRegister(cashRegisterService.findCashRegister(new Long(1)));
		return cashReceipt;
	}
	
	public static EncashmentSession getActiveEncashmentSession(){
		Assert.notNull(encashmentSessions, "no encashment session");
		for (EncashmentSession encashmentSession : encashmentSessions) {
			if(encashmentSession.IS_OPEN) return encashmentSession;
		}
		return null;
	}
	public static void addEncashmentSession(EncashmentSession encashmentSession){
		Assert.notNull(encashmentSession, "the encasssemnt session might not be null");
		if(encashmentSessions == null ) encashmentSessions = new ArrayList<EncashmentSession>();
		encashmentSessions.add(encashmentSession);
	}

	@Override
	public String toString() {
		return "BasicEncashment ["+encashmentSessions.toString()+"]";
	}
	
}